﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;

namespace JM.JCY.SharePointComponent.PhotoAlbum.AddAlbum
{
    public partial class AddAlbumUserControl : UserControl
    {
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        public DataTable sessionKeys
        {
            get
            {
                DataTable dt = new DataTable();
                DataColumn dc = new DataColumn();
                dc.ColumnName = "fileType";
                dt.Columns.Add(dc);

                DataColumn dc2 = new DataColumn();
                dc2.ColumnName = "fileKey";
                dt.Columns.Add(dc2);

                DataColumn dc3 = new DataColumn();
                dc3.ColumnName = "fileTypeName";
                dt.Columns.Add(dc3);

                DataColumn dc4 = new DataColumn();
                dc4.ColumnName = "filePath";
                dt.Columns.Add(dc4);

                DataColumn dc5 = new DataColumn();
                dc5.ColumnName = "orgFileName";
                dt.Columns.Add(dc5);

                return dt;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadApplicationContext();
            if (!IsPostBack)
            {
                LoadWorkgroupAndCommittee();
            }
            string CreateAlbum = Request.Params.Get("__EVENTTARGET");
            if (CreateAlbum != null && CreateAlbum.IndexOf("CreateAlbum") > -1)
            {
                BtnSave_Click(null, null);
            }
        }

        private void LoadWorkgroupAndCommittee()
        {
            RadioButtonListPlace.Items.Clear();
            RadioButtonListPlace.Items.Add(new ListItem("公开", "Public_0"));
            using (PhotoAlbumProxy accessProxy = new PhotoAlbumProxy())
            {
                PhotoAlbumSearchDataSet.T_UserDepartmentDataTable department = accessProxy.GetUserDepartmentByUserId(_staffId);
                foreach (PhotoAlbumSearchDataSet.T_UserDepartmentRow row in department)
                {
                    RadioButtonListPlace.Items.Add(new ListItem(row.DeptName, "Workgroup_" + row.DepartmentId.ToString()));
                }

                PhotoAlbumSearchDataSet.T_UserCommitteeDataTable committee = accessProxy.GetUserCommitteeByUserId(_staffId);
                foreach (PhotoAlbumSearchDataSet.T_UserCommitteeRow row in committee)
                {
                    RadioButtonListPlace.Items.Add(new ListItem(row.CommitteeName, "Committee_" + row.CommitteeId.ToString()));
                }
            }
            //RadioButtonListPlace.Items.Add(new ListItem("个人", "Personal_" + _staffId.ToString()));
            RadioButtonListPlace.Items[0].Selected = true;
        }
        private void LoadApplicationContext()
        {
            _staffId = 11;
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
            }

            if (ApplicationContext.Current.GetKeyValue("appType") != null)
            {
                appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
            }

            switch (appType)
            {
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                    appId = 0;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                    appId = _staffId;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
            }
        }
        protected void BtnSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                string selected = RadioButtonListPlace.SelectedItem.Value;
                string[] values = selected.Split(new char[] { '_' });
                DataTable tableKeys = getFilesDetailToDataTable();
                SPWeb CurrentWeb = SPContext.Current.Web;
                string siteName = string.Empty;
                int albumId = 0;
                switch (values[0])
                {
                    case "Public":
                        siteName = string.Empty;
                        appType = JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName;

                        appId = 0;
                        break;
                    case "Personal":
                        siteName = JCYConstant.SiteUrlName.MySite;
                        appId = _staffId;
                        appType = JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName;
                        break;
                    case "Workgroup":
                        siteName = JCYConstant.SiteUrlName.MyDept;
                        appId = Convert.ToInt32(values[1]);
                        appType = JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName;
                        break;
                    case "Committee":
                        siteName = JCYConstant.SiteUrlName.MyCommittee;
                        appId = Convert.ToInt32(values[1]);
                        appType = JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName;
                        break;
                }

                ApplicationContext.Current.SetKeyValue("AppId", appId);
                ApplicationContext.Current.SetKeyValue("appType", appType);
                using (PhotoAlbumProxy funProxy = new PhotoAlbumProxy())
                {
                    SPInputs createAlbumInput = new SPInputs();
                    List<byte[]> mediaList = new List<byte[]>();
                    List<string> mediaExtension = new List<string>();
                    DataTable mediaTable = new DataTable();
                    DataColumn dc1 = new DataColumn();
                    dc1.ColumnName = "FilePath";
                    mediaTable.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn();
                    dc2.ColumnName = "PicPath";
                    mediaTable.Columns.Add(dc2);

                    #region ready data for inputs
                    string picName=string.Empty;
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        picName = Guid.NewGuid().ToString().Replace("-", "");
                        if (keyRow["fileType"].ToString().Equals("pic"))
                        {
                            // pic type
                            mediaExtension.Add("." + keyRow["fileTypeName"].ToString());
                            if (Session[keyRow["fileKey"].ToString()] != null)
                            {
                                byte[] mediaStream = (byte[])Session[keyRow["fileKey"].ToString()];
                                mediaList.Add(mediaStream);
                            }
                        }
                    }

                    createAlbumInput.MediaStream = mediaList;
                    createAlbumInput.MediaExtension = mediaExtension;
                    createAlbumInput.ApplicationType = appType;
                    createAlbumInput.SiteName = siteName;
                    createAlbumInput.ContextID =appId.ToString();
                    createAlbumInput.AlbumName = this.txtAlbumName.Text;
                    createAlbumInput.MediaTable =null;// mediaTable;

                    createAlbumInput.SharingOption = "";
                    #endregion

                    SPOutputs spout = JCYSharePointHelper.CreateFolderWithUpload(createAlbumInput);
                    if (!spout.IsError)
                    {
                        #region insert Data to DB
                        DataTable outTable = spout.OutputsTable;
                        string picFolderID = string.Empty, mediaFolderID = string.Empty;

                        var albumDS = new PhotoAlbumDataSet();
                        foreach (DataRow r in outTable.Rows)
                        {
                            if (r[1].ToString().Equals(string.Empty))
                            {

                                picFolderID = r["FolderID"].ToString();
                                r.Delete();
                                break;
                            }
                        }
                        //AccessFrameworkDataSet.T_OcpApplicationDataTable applicationdt;
                        //applicationdt = GetApplicationByName(OCPConstant.ListName.FunWork);

                        var newAlbumRow = albumDS.T_Album.NewT_AlbumRow();
                        for (int i = 0; i < outTable.Rows.Count; i++)
                        {
                            DataRow outRow = outTable.Rows[i];
                            //insert album table
                            if (i == 0)
                            {
                                //insert sharepoint object table.
                                var newAlbumObjectRow = albumDS.T_SharePointObject.NewT_SharePointObjectRow();
                                newAlbumObjectRow.SPSiteName = appType;
                                newAlbumObjectRow.SPListName = appType;
                                newAlbumObjectRow.SPFolderId = picFolderID;
                                newAlbumObjectRow.IsDeleted = false;

                               JCYUtility.UpdateCommonFields(newAlbumObjectRow, "a");
                                albumDS.T_SharePointObject.AddT_SharePointObjectRow(newAlbumObjectRow);

                                //insert album table
                                newAlbumRow.SharePointObjectId = newAlbumObjectRow.SharePointObjectId;
                                newAlbumRow.Name = this.txtAlbumName.Text;
                                newAlbumRow.Description = this.txtAlbumDescription.Text.Length > 256 ? this.txtAlbumDescription.Text.Substring(0, 256) : this.txtAlbumDescription.Text;
                                newAlbumRow.ItemCount = 0;
                                newAlbumRow.ViewCount = 0;
                                newAlbumRow.LikeCount = 0;
                                newAlbumRow.AppId = appId;
                                newAlbumRow.AppType = appType;
                                newAlbumRow.Creator = _staffId;
                                newAlbumRow.LatestUpdateTime = DateTime.Now;
                                newAlbumRow.IsDeleted = false;
                                newAlbumRow.ThumbNailImgUrl = "";
                                JCYUtility.UpdateCommonFields(newAlbumRow, "a");
                                albumDS.T_Album.AddT_AlbumRow(newAlbumRow);
                            }

                            // insert sharepoint object table

                            var newObjectRow = albumDS.T_SharePointObject.NewT_SharePointObjectRow();
                            newObjectRow.SPSiteName = appType;
                            newObjectRow.SPListName ="";
                            newObjectRow.SPFolderId = outRow["FolderID"].ToString();
                            newObjectRow.SPListItemId = outRow["ItemID"].ToString();
                            newObjectRow.IsDeleted = false;
                            JCYUtility.UpdateCommonFields(newObjectRow, "a");
                            albumDS.T_SharePointObject.AddT_SharePointObjectRow(newObjectRow);

                            // insert album content table  
                            var newAlbumContentRow = albumDS.T_AlbumContent.NewT_AlbumContentRow();
                            newAlbumContentRow.AlbumId = newAlbumRow.AlbumId;
                            newAlbumContentRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                            newAlbumContentRow.OriginalImgUrl = outRow["OriginalImgUrl"].ToString();
                            newAlbumContentRow.OptimizeImgUrl = outRow["OptimizeImgUrl"].ToString();
                            newAlbumContentRow.StaffId = _staffId;
                            newAlbumContentRow.Description = string.Empty;
                            newAlbumContentRow.IsDeleted = false;
                            newAlbumContentRow.SharePointObjectId = newObjectRow.SharePointObjectId;
                            JCYUtility.UpdateCommonFields(newAlbumContentRow, "A");
                            albumDS.T_AlbumContent.AddT_AlbumContentRow(newAlbumContentRow);
                            newAlbumRow.ItemCount += 1;
                            newAlbumRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                        }

                        funProxy.CreateAlbumwithUpload(albumDS);
                        albumId = albumDS.T_Album[0].AlbumId;
                        #endregion
                    }
                    else
                    {
                        return;
                    }
                    //clear all session byte[].
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        if (Session[keyRow["fileKey"].ToString()] != null)
                        {
                            Session.Remove(keyRow["fileKey"].ToString());
                        }
                    }
                    tableKeys.Rows.Clear();
                }

                //Response.Redirect(siteurl + siteName + "JCYPages/PhotoAlbum/ViewAlbum.aspx?AlbumId=" + albumId);
                //update by JiangMin
                Response.Redirect(SPContext.Current.Site.ServerRelativeUrl + "PhotoAlbumPages/ViewAlbum.aspx?AlbumId=" + albumId);
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("create album", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }
        }

        public DataTable getFilesDetailToDataTable()
        {
            DataTable dt = sessionKeys;
            try
            {
                string uploadPath = System.Configuration.ConfigurationManager.AppSettings["uploadPath"].ToString();
                uploadPath = Context.Server.MapPath(uploadPath);
                if (uploadPath.EndsWith("\\") == false)
                {
                    uploadPath = uploadPath + "\\";
                }

                string logFileName = HiddenFieldGuid.Value.Replace("-", "") + ".txt";
                if (File.Exists(uploadPath + logFileName))
                {
                    string[] fileLines = File.ReadAllLines(uploadPath + logFileName);

                    foreach (string stg in fileLines)
                    {
                        string[] fileDetail = stg.Split(new char[] { '?' });
                        DataRow row = dt.NewRow();
                        //row["fileType"] = "pic";
                        //row["filePath"] = uploadPath + fileName;
                        //row["fileTypeName"] = fileTypeName;
                        //row["orgFileName"] = file.FileName;
                        if (fileDetail[0].Equals("pic"))
                        {
                            FileStream fs = new FileStream(fileDetail[1], FileMode.Open, FileAccess.Read);
                            byte[] fileBuffer = new byte[fs.Length];
                            fs.Read(fileBuffer, 0, fileBuffer.Length);
                            fs.Close();
                            fs.Dispose();

                            string fileKey = Guid.NewGuid().ToString();
                            Session[fileKey] = fileBuffer;

                            row["fileType"] = fileDetail[0];
                            row["fileKey"] = fileKey;
                            row["filePath"] = fileDetail[1];
                            row["fileTypeName"] = fileDetail[2];
                            row["orgFileName"] = fileDetail[3];

                        }
                        dt.Rows.Add(row);
                    }
                }
                else
                {
                    throw new Exception("Can not find files log detail information:" + uploadPath + logFileName);
                }
            }
            catch (Exception ex)
            {
                JCYUtility.ExceptionHandle("getFilesDetails", ex);
            }

            return dt;
        }
    }
}
